//
//  SBCategaryBar.m
//  GomeEShop
//
//  Created by tangli on 15/3/10.
//  Copyright (c) 2015年 Gome. All rights reserved.
//

#import "GMCategaryBar.h"
#import <MPUmeng.h>

@interface GMCategaryBar()

@property (nonatomic, strong) NSMutableArray *mary; // 标签文字数组

@property (nonatomic, weak) UIView *viewRedDivider; // 红线

@property (nonatomic, strong) NSMutableArray *maryBtn; // 存放标签的按钮数组;

@property (nonatomic, strong) UIButton *btnSelected;  // 纪录选中状态的按钮

@property (nonatomic, weak) UIView *viewCategary;

@property (nonatomic, assign) BOOL isEqualBtn;  // 初始化红线的X值是否等于0（yes为定于0）

@property (nonatomic,assign) NSInteger intIndex; // 纪录当前按钮的索引

@end

@implementation GMCategaryBar

/// 存放标签的按钮数组懒加载
- (NSMutableArray *)maryBtn
{
    if (_maryBtn == nil)
    {
        _maryBtn = [NSMutableArray array];
    }
    return _maryBtn;
}


/*!
 *  @Author tangli, 15-03-05 18:03:41
 *
 *  @brief  实例化对象方法
 *
 *  @array  标签文字数组
 *
 *  @since  4.0.8
 */
- (instancetype)initWithCategaryBarWithArrayTitle:(NSArray *)ary
                               dividerIsEqualBtnW:(BOOL)isEqualBtn
{
    if (self = [super init])
    {
        self.mary = [NSMutableArray arrayWithArray:ary];
        
        self.isEqualBtn = isEqualBtn;
        
        // 如果数组中的数据是0或1时不做任何处理
        if (ary.count == 0 ||ary.count == 1)
        {
            return self;
        }
        
        // 创建SBCategaryBar对象
        self.frame = CGRectMake(0,GMK_NavBar_H, screenW,CATEGARYBAR_H);
        self.backgroundColor = [UIColor whiteColor];
        
        // 创建SBCategaryBar整体内容的View
        UIView *categaryView = [[UIView alloc] init];
        categaryView.backgroundColor = RGBAColor(254, 222, 9, 1);
        self.viewCategary = categaryView;
        [self addSubview:categaryView];
        
        NSInteger intCount = ary.count;
        
        categaryView.frame = CGRectMake(0, 0, screenW, CATEGARYBAR_H);
            
        for (NSInteger i = 0 ; i < intCount; i ++)
        {
            // 创建按钮
            CGFloat fltBtnY = 20;
            CGFloat fltBtnW = 46;
            CGFloat fltBtnH = 44;
            if (i == 0)
            {
                [self createBtn:ary[i]
                   withBtnFrame:CGRectMake((screenW - 46 * 3 - 40) / 2, fltBtnY, fltBtnW, fltBtnH)
                withCategaryBar:categaryView
                      withIndex:i];
            }
            else if (i == 1)
            {
                [self createBtn:ary[i]
                   withBtnFrame:CGRectMake((screenW - 46 * 3- 40) / 2 + 20 + fltBtnW, fltBtnY, fltBtnW, fltBtnH)
                withCategaryBar:categaryView
                      withIndex:i];
            }
            else
            {
                [self createBtn:ary[i]
                   withBtnFrame:CGRectMake((screenW - 46 * 3- 40) / 2 + 40 + 2*fltBtnW, fltBtnY, fltBtnW, fltBtnH)
                withCategaryBar:categaryView
                      withIndex:i];
            }
        }
        
        
        // 创建红线
        UIView *viewRedDivider = [[UIView alloc] init];
        viewRedDivider.backgroundColor = RGBAllColor(0x282828);
        UIButton *btn = [_maryBtn objectAtIndex:0];
        viewRedDivider.frame = CGRectMake(0, CATEGARYBAR_H - 4, btn.frame.size.width, 4);
        viewRedDivider.center = CGPointMake(btn.center.x, viewRedDivider.center.y);
        
        // 创建SBCategaryBar底部的分割线
        UIView *viewDivider = [[UIView alloc]init];
        viewDivider.frame = CGRectMake(0, CATEGARYBAR_H - 0.6, _viewCategary.frame.size.width, 0.6);
        viewDivider.backgroundColor = RGBAllColor(0xB2B2B2);
        [self addSubview:viewDivider];

        
        self.viewRedDivider = viewRedDivider;
        [self addSubview:viewRedDivider];
        
        // 设置categaryBar的内容尺寸
        self.contentSize = categaryView.frame.size;
        
        // 隐藏水平方向的滚动条
        self.showsHorizontalScrollIndicator = NO;
        // 隐藏竖直方向的滚动条
        self.showsVerticalScrollIndicator = NO;
        
        //    // 取消弹簧效果
        //    categaryBar.bounces =NO;
        
        //增加上中左右额外的区域
        self.contentInset =UIEdgeInsetsMake(0, 0, 0, 0);
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClicked)];
        tap.numberOfTapsRequired = 2;
        [self addGestureRecognizer:tap];
        
        [MPUmeng event:@"TabHomePageShow" attributes:@{@"page":@"hot"}];
        
    }
    
    return self;
}

/*!
 *  @Author tangli, 15-03-05 18:03:41
 *
 *  @brief  初始化变量
 *
 *  @array  标签文字数组
 *
 *  @return 返回分类分类导航栏对象
 *
 *  @since  4.0.8
 */
+ (instancetype)categaryBarWithArrayTitle:(NSArray *)ary
                       dividerIsEqualBtnW:(BOOL)isEqualBtn
{
    return [[self alloc]initWithCategaryBarWithArrayTitle:ary dividerIsEqualBtnW:isEqualBtn];
}

/*!
 *  @Author tangli, 15-03-05 18:03:41
 *
 *  @brief  创建标签按钮
 *
 *  @since  4.0.8
 */
- (UIButton *)createBtn:(NSString *)title
            withBtnFrame:(CGRect)frame
        withCategaryBar:(UIView *)categaryView
              withIndex:(NSInteger)intIndex
{
    UIButton *btn = [[UIButton alloc]init];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:RGBAllColor(0x6F6200) forState:UIControlStateNormal];
    [btn setTitleColor:RGBColor(0x28, 0x28, 0x28) forState:UIControlStateSelected];
    [btn.titleLabel setFont:[UIFont boldSystemFontOfSize:FounSize]];
    btn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    btn.frame = frame;
    
    if (intIndex == 0) // 默认第一个按钮文字为选中状态
    {
        btn.selected = YES;
        self.btnSelected = btn;
    }
    
    [categaryView addSubview:btn];
    
    [self.maryBtn addObject:btn]; // 把标签按钮添加到数组中
    
    return btn;
}

/*!
 *  @Author tangli, 15-03-05 18:03:41
 *
 *  @brief  标签按钮点击事件
 *
 *  @since  4.0.8
 */
- (void)btnClick:(UIButton *)btnSender
{
    NSInteger intIndex = [self.mary indexOfObject:btnSender.currentTitle];
    
    if (self.intIndex == intIndex)  // 如果点击同一个按钮，则返回
    {
        return;
    }
    NSString *pageName = (intIndex>-1&&intIndex<3) ? @[@"hot",@"feed",@"new"][intIndex] : @"unknow";
    [MPUmeng event:@"TabHomePageShow" attributes:@{@"page":pageName}];
    
    self.btnSelected.selected = NO;
    btnSender.selected = YES;
    self.btnSelected = btnSender;
    
    // 红线的fram改变
    [self scrollDivider:btnSender];
    
    // 代理方法调用
    if ([self.delegateCategary respondsToSelector:@selector(categaryBarOptionalDelegate:withBtnIndex:)])
    {
        [self.delegateCategary categaryBarOptionalDelegate:self withBtnIndex:intIndex];
    }
    
    [self selectBtnCenter:intIndex withBtn:btnSender];
}

/*!
 *  @Author tangli, 15-03-05 18:03:41
 *
 *  @brief  当滑动底下的View时，分类bar中的标签按钮下的红线也会自动滑动
 *
 *  @intIndex  滑向标签按钮的索引（以0开始）
 *
 *  @since   4.0.8
 */
- (void)automaticScrollDivider:(NSInteger)intIndex
{
    // 添加数据保护
    if (intIndex >= self.maryBtn.count)
    {
        return;
    }
    // 根据标签的索引查找对应标签的按钮
    UIButton *btnSender = [self.maryBtn objectAtIndex:intIndex];
    
    // 设置按钮选中时的文字颜色为红色
    self.btnSelected.selected = NO;
    btnSender.selected = YES;
    self.btnSelected = btnSender;
    
    // 把按钮字体设为红色
    [btnSender setTitleColor:RGBAllColor(0x6F6200) forState:UIControlStateNormal];
    
    // 红线的fram改变
    [self scrollDivider:btnSender];
    
    // 使选中的按钮居中显示
    [self selectBtnCenter:intIndex withBtn:btnSender];
    
}

// 此方法的功能是使选中的按钮居中显示
- (void)selectBtnCenter:(NSInteger)intIndex withBtn:(UIButton *)btnSender
{
    CGPoint senderCenter = btnSender.center; // 获取按钮的中点
    CGFloat fltBtnDistanceScreen = senderCenter.x - self.contentOffset.x; // 按钮离窗口的X值
    
    // 获取categaryBar剩余的长度
    CGFloat fltShengyu = self.viewCategary.frame.size.width - self.contentOffset.x;
    
    // 当索引增加时，categaryBar待显示的剩余长度要大于屏幕宽度，并且按钮中点要大于屏幕中点
    BOOL isIndexAdd = (fltShengyu > screenW)
    && (self.intIndex < intIndex)
    && (fltBtnDistanceScreen > screenW / 2);
    
    // 当索引减少时，并且选中按钮中点要大于屏幕中点
    BOOL isIndexReduce = (self.intIndex >= intIndex) && self.contentOffset.x >= 0;
    
    // 当按钮的索引增加或减少时，且其中点不等于屏幕的中点时，自动滑动categaryBar相应的距离，使其居中
    if ((fltBtnDistanceScreen != screenW / 2 && isIndexAdd) ||
        (fltBtnDistanceScreen != screenW / 2 && isIndexReduce) )
    {
        CGFloat fltOldOffsetX = self.contentOffset.x;  // 当前的偏移量
        CGFloat fltNewOffsetX = fltOldOffsetX + fltBtnDistanceScreen - screenW / 2; // 新的偏移量
        
        // 当索引增加时，新的偏移量超出了范围只滑动categaryBar剩余的长度即可
        if (fltNewOffsetX + screenW > self.viewCategary.frame.size.width)
        {
            fltNewOffsetX = fltOldOffsetX + self.viewCategary.frame.size.width - fltOldOffsetX - screenW;
        }
        
        // 当索引减少时，新的偏移量超出了范围只滑动categaryBar剩余的长度即可
        if (fltNewOffsetX < 0)
        {
            fltNewOffsetX = 0;
        }
        
        // 自动滑动categaryBar的相应的距离
        [self setContentOffset:CGPointMake(fltNewOffsetX, 0) animated:YES];
    }
    self.intIndex = intIndex; // 纪录前一个按钮的索引
}

/*!
 *  @Author tangli, 15-03-05 18:03:41
 *
 *  @brief  分类bar中的标签中红线滑动
 *
 *  @since   4.0.8
 */
- (void)scrollDivider:(UIButton *)btnSender
{
    // 判断红线的X值是否是从标签按钮开始的
    [UIView animateWithDuration:0.3 animations:^
     {
         self.viewRedDivider.center = CGPointMake(btnSender.center.x, self.viewRedDivider.center.y);
     }];
}

/*!
 *  @Author tangli, 15-03-05 18:03:41
 *
 *  @brief  删除按钮，跳到首个按钮
 *
 *  @intIndex  删除按钮的索引
 *
 *  @since   4.0.8
 */
- (void)deleteBtnWithIndex:(NSInteger)intIndex
{
    // 添加数据保护
    if (intIndex >= self.maryBtn.count)
    {
        return;
    }
    
    UIButton *btn = [self.maryBtn objectAtIndex:intIndex];
    
    self.intIndex = 0;  // 删除按钮即跳到第0个索引
    
    // 根据指定的索引删除按钮数组中的元素
    [self.maryBtn removeObjectAtIndex:intIndex];
    
    // 根据指定的索引删除标签文字数组的元素
    [self.mary removeObjectAtIndex:intIndex];
    
    // 把要删除的按钮从分类Bar上移除
    [btn removeFromSuperview];
    
    NSInteger intCount = _mary.count;
    CGFloat fltTotalW = 0; // 所有按钮的总宽
    for (NSInteger i = 0; i < intCount; i ++) // 根据传来的标签文字计算每个按钮的宽度总和，判断是否超屏
    {
        NSString *strTitle = _mary[i];
        
        CGSize size = [strTitle sizeWithFont:[UIFont systemFontOfSize:FounSize]
                        constrainedToSize:CGSizeMake(MAXFLOAT, MAXFLOAT)
                            lineBreakMode:NSLineBreakByCharWrapping];
        
        CGFloat fltBtnW = size.width + Padding * 2; // 计算按钮宽度
        
        fltTotalW = fltTotalW + fltBtnW; // 所有按钮的总宽
    }
    
    self.viewCategary.frame = CGRectMake(0, 0, screenW, CATEGARYBAR_H);
    for (NSInteger i = 0;i < intCount;i++)
    {
        UIButton *btn = self.maryBtn[i];
        
        // 重新设置每个按钮的fram
        CGFloat fltBtnY = 0;
        CGFloat fltBtnW = screenW / intCount;
        CGFloat fltBtnH = CATEGARYBAR_H;
        CGFloat fltBtnX = i * fltBtnW;
        btn.frame = CGRectMake(fltBtnX, fltBtnY, fltBtnW, fltBtnH);
    }
    // 跳到首个按钮
    // 设置按钮选中时的文字颜色为红色
    UIButton *btnFirst = self.maryBtn[0];
    self.btnSelected.selected = NO;
    btnFirst.selected = YES;
    self.btnSelected = btnFirst;
    
    // 滚动红线到相应位子
    [self scrollDivider:btnFirst];
}

- (void)tapClicked
{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"tablebviewToTop" object:nil];
}

@end
